package com.njiandan.johnson.vr360;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.njiandan.johnson.vr360library.VrMediaPlayerWrapper;
import com.njiandan.johnson.vr360library.VrPlayerActivity;
import com.njiandan.johnson.vr360library.VrUIController;
import com.njiandan.johnson.vr360library.VrViewWrapper;
import com.njiandan.johnson.vr360library.constant.VrMode;
import com.njiandan.johnson.vr360library.constant.VrStatus;
import com.njiandan.johnson.vr360library.utils.UIUtils;

/**
 * author：johnsonZhang on 2017/3/29 18:04
 * email：15915356@qq.com
 */
public class PlanePlayerActivity extends AppCompatActivity implements View.OnClickListener {

    private VrUIController mVrUIController;
    private VrViewWrapper mVrViewWrapper;
    private RelativeLayout mRltContent;
    private ImageView mImgBufferAnim;

    /**
     * 是否是全屏播放
     */
    private boolean mIsFullScreen = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);

        setContentView(R.layout.activity_plane_player);

        getContentResolver().registerContentObserver(Settings.System.getUriFor(
                Settings.System.ACCELEROMETER_ROTATION), true, rotationObserver);

        init();
    }

    private ContentObserver rotationObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            if (selfChange) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
            }
        }
    };

    private void init() {
        String videoPath = getIntent().getStringExtra(VrPlayerActivity.VIDEO_PATH);
        boolean imageMode = getIntent().getBooleanExtra(VrPlayerActivity.IMAGE_MODE, false);
        boolean planeMode = getIntent().getBooleanExtra(VrPlayerActivity.PLANE_MODE, false);
        boolean windowMode = getIntent().getBooleanExtra(VrPlayerActivity.WINDOW_MODE, false);
        ImageView imgFullScreen = (ImageView) findViewById(com.njiandan.johnson.vr360library.R.id.img_full_screen);
        imgFullScreen.setVisibility(windowMode ? View.VISIBLE : View.GONE);
        imgFullScreen.setOnClickListener(this);
        mRltContent = (RelativeLayout) findViewById(R.id.rlt_content);

        mImgBufferAnim = (ImageView) findViewById(com.njiandan.johnson.vr360library.R.id.activity_imgBuffer);
        UIUtils.setBufferVisibility(mImgBufferAnim, !imageMode);
        mVrUIController = new VrUIController(
                (RelativeLayout) findViewById(com.njiandan.johnson.vr360library.R.id.player_toolbar_control),
                (RelativeLayout) findViewById(com.njiandan.johnson.vr360library.R.id.player_toolbar_progress),
                this, imageMode);

        TextView title = (TextView) findViewById(com.njiandan.johnson.vr360library.R.id.video_title);
        title.setText(Uri.parse(videoPath).getLastPathSegment());
        GLSurfaceView glSurfaceView = (GLSurfaceView) findViewById(com.njiandan.johnson.vr360library.R.id.surface_view);

        mVrViewWrapper = VrViewWrapper.with(this)
                .setVideoPath(videoPath)
                .setGlSurfaceView(glSurfaceView)
                .setImageMode(imageMode)
                .setPlaneMode(planeMode)
                .init();

        glSurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mVrUIController.startHideControllerTimer();
                return mVrViewWrapper.handleTouchEvent(event);
            }
        });
        mVrUIController.setAutoHideController(true);
        mVrUIController.setUiCallback(new VrUIController.UICallback() {
            @Override
            public void requestScreenshot() {
                mVrViewWrapper.getTouchHelper().shotScreen();
            }

            @Override
            public void requestFinish() {
                if (mIsFullScreen) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    finish();
                }
            }

            @Override
            public void changeDisPlayMode() {
                if (mVrViewWrapper.getStatusHelper().getVrDisPlayMode() == VrMode.DUAL_SCREEN)
                    mVrViewWrapper.getStatusHelper().setVrDisPlayMode(VrMode.SINGLE_SCREEN);
                else mVrViewWrapper.getStatusHelper().setVrDisPlayMode(VrMode.DUAL_SCREEN);
            }

            @Override
            public void changeInteractiveMode() {
                if (mVrViewWrapper.getStatusHelper().getVrInteractiveMode() == VrMode.MOTION)
                    mVrViewWrapper.getStatusHelper().setVrInteractiveMode(VrMode.TOUCH);
                else mVrViewWrapper.getStatusHelper().setVrInteractiveMode(VrMode.MOTION);
            }

            @Override
            public void changePlayingStatus() {
                if (mVrViewWrapper.getStatusHelper().getVrStatus() == VrStatus.PLAYING) {
                    mVrViewWrapper.getMediaPlayer().pauseByUser();
                } else if (mVrViewWrapper.getStatusHelper().getVrStatus() == VrStatus.PAUSED_BY_USER) {
                    mVrViewWrapper.getMediaPlayer().start();
                }
            }

            @Override
            public void playerSeekTo(int pos) {
                mVrViewWrapper.getMediaPlayer().seekTo(pos);
            }

            @Override
            public int getPlayerDuration() {
                return mVrViewWrapper.getMediaPlayer().getDuration();
            }

            @Override
            public int getPlayerCurrentPosition() {
                return mVrViewWrapper.getMediaPlayer().getCurrentPosition();
            }
        });
        mVrViewWrapper.getTouchHelper().setPanoUIController(mVrUIController);

        if (!imageMode) {
            mVrViewWrapper.getMediaPlayer().setPlayerCallback(new VrMediaPlayerWrapper.PlayerCallback() {
                @Override
                public void updateProgress() {
                    mVrUIController.updateProgress();
                }

                @Override
                public void updateInfo() {
                    UIUtils.setBufferVisibility(mImgBufferAnim, false);
                    mVrUIController.startHideControllerTimer();
                    mVrUIController.setInfo();
                }

                @Override
                public void requestFinish() {
                    if (mIsFullScreen) {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }
                }
            });
        } else mVrUIController.startHideControllerTimer();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mVrViewWrapper.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mVrViewWrapper.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVrViewWrapper.releaseResources();
        getContentResolver().unregisterContentObserver(rotationObserver);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_full_screen:
                if (!mIsFullScreen) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setFullScreenPlay();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            setWindowScreenPlay();
        }
    }

    private void setFullScreenPlay() {
        mIsFullScreen = true;

        // 设置全屏即隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        // 设置视频充满全屏
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mRltContent.getLayoutParams();
        layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
        layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
        mRltContent.setLayoutParams(layoutParams);
    }

    private void setWindowScreenPlay() {
        mIsFullScreen = false;

        // 恢复状态栏
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(attrs);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        // 设置显示视频固定大小
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mRltContent.getLayoutParams();
        layoutParams.height = DimenUtils.dp2px(this, 230);
        layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
        mRltContent.setLayoutParams(layoutParams);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mIsFullScreen) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
